#include <header.h>

//方法1.系统日志
#define LOG_INFO_MSG(message) \
    do { \
        syslog(LOG_INFO, "[INFO]%s", message); \
    } while(0)



//方法2.写进当前目录下的日志
//客户端请求信息（连接时间）
#define LOG_CLIENT_REQUEST(client_ip) \
    do { \
        int log_fd = open("client.log", O_WRONLY | O_APPEND | O_CREAT, 0644); \
        if (log_fd != -1) { \
            time_t now = time(NULL); \
            struct tm *timeinfo = localtime(&now); \
            char time_str[20]; \
            strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo); \
            char log_message[256]; \
            snprintf(log_message, sizeof(log_message), "[INFO] Client IP: %s connected at %s\n", client_ip, time_str); \
            write(log_fd, log_message, strlen(log_message)); \
            close(log_fd); \
        } \
    } while(0)

//客户端操作信息（操作时间）
#define LOG_CLIENT_OPERATION(client_ip, operation) \
    do { \
        int log_fd = open("client.log", O_WRONLY | O_APPEND | O_CREAT, 0644); \
        if (log_fd != -1) { \
            time_t now = time(NULL); \
            struct tm *timeinfo = localtime(&now); \
            char time_str[20]; \
            strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo); \
            char log_message[256]; \
            snprintf(log_message, sizeof(log_message), "[INFO] Client IP: %s performed operation: %s at %s\n", client_ip, operation, time_str); \
            write(log_fd, log_message, strlen(log_message)); \
            close(log_fd); \
        } \
    } while(0)


//单元测试
int main(){
    // 查看系统日志  cat /var/log/syslog|grep 文件名
    LOG_INFO_MSG("this is test for log");
    const char *client_ip = "192.168.1.100";
    LOG_CLIENT_REQUEST(client_ip);  // 记录客户端请求和连接时间
    while(1){
        sleep(10);
        const char *operation = "Login";
        LOG_CLIENT_OPERATION(client_ip, operation);  // 记录客户端操作和操作时间
    }
    return 0;
}
